package com.bp.hearthealth.pulse.lnapps.ads.admob.native_ad

import com.bp.hearthealth.pulse.lnapps.BpApplication
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsCount
import com.bp.hearthealth.pulse.lnapps.ads.model.AdsSwitch
import com.bp.hearthealth.pulse.lnapps.ads.timer.TimerObserver
import com.bp.hearthealth.pulse.lnapps.bp_extension.LogUtil
import com.bp.hearthealth.pulse.lnapps.bp_utils.Constants
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdLoader
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdOptions

object AdMobNativeAdManager : TimerObserver {
    private var nativeAds: MutableList<NativeAd> = mutableListOf()

    private var adUnitIds: MutableList<String> = mutableListOf()
    private var adListener: AdMobNativeAdListener? = null
    private var numberRetries = 0
    private var loading = true

    fun setNativeAdListener(listener: AdMobNativeAdListener?) {
        if (listener != null && !AdsSwitch.getBoolean(AdsSwitch.adNativeControl)) {
            return
        }
        adListener = listener
    }

    fun loadNativeAds(
        adUnitIds: MutableList<String>
    ) {
        AdMobNativeAdManager.adUnitIds = adUnitIds
        if (!AdsSwitch.getBoolean(AdsSwitch.adNativeControl)) {
            return
        }
        val adLoader = AdLoader.Builder(
            BpApplication.context, adUnitIds.joinToString(separator = ",")
        ).forNativeAd { loadedNativeAd ->
            loading = false
            nativeAds.add(0, loadedNativeAd)
            adListener?.onAdLoaded(nativeAds)
            LogUtil.i("已加载到原生广告")
//            LogUtil.i("已加载到原生广告，数量为：${nativeAds.size}")
//            LogUtil.i("原生广告来源：${loadedNativeAd.headline}")
        }.withAdListener(object : AdListener() {
            override fun onAdClicked() {
                AdsCount.incrementClickCount()
                adListener?.onAdClicked()
                LogUtil.i("原生广告：onAdClicked")
            }

            override fun onAdClosed() {
                adListener?.onAdClosed()
                LogUtil.i("原生广告：onAdClicked")
            }

            override fun onAdFailedToLoad(var1: LoadAdError) {
                loading = false
                if (numberRetries < 3) {
                    loadNativeAds(mutableListOf(Constants.Native_Advanced))
                }
                numberRetries++
                adListener?.onAdFailedToLoad(var1)
                LogUtil.i("原生广告：onAdFailedToLoad $var1")
            }

            override fun onAdImpression() {
                adListener?.onAdImpression()
                LogUtil.i("原生广告：onAdImpression")
            }

            override fun onAdOpened() {
                adListener?.onAdOpened()
                LogUtil.i("原生广告：onAdOpened")
            }

            override fun onAdSwipeGestureClicked() {
                adListener?.onAdSwipeGestureClicked()
                LogUtil.i("原生广告：onAdSwipeGestureClicked")
            }
        }).withNativeAdOptions(NativeAdOptions.Builder().build()).build()
        adLoader.loadAds(AdRequest.Builder().build(), adUnitIds.size)
    }

    private fun releaseNativeAds() {
        if (nativeAds.isNotEmpty()) {
            val iterator = nativeAds.iterator()
            while (iterator.hasNext()) {
                val ad = iterator.next()
                ad.destroy()
                iterator.remove()
            }
//            LogUtil.i("原生剩余原生广告个数：${nativeAds.size}")
        }
    }

    //获取集合
    fun getNativeAds(): MutableList<NativeAd> {
        if (!AdsSwitch.getBoolean(AdsSwitch.adNativeControl)) {
            return mutableListOf()
        }
        if (numberRetries >= 2) {
            LogUtil.i("原生广告加载失败已超过3次")
            numberRetries = 0
            loadNativeAds(adUnitIds)
        }
        return nativeAds
    }

    /**
     * 原生广告对象释放掉后点击事件无效；
     * 移除当前页监听 & 预加载一条数据；
     * 广告显示完调用
     */
    fun removeUsedNativeAdListener() {
        setNativeAdListener(null)
        if (!loading) {
//            LogUtil.i("移除监听后，预加载原生广告")
            loadNativeAds(adUnitIds)
            loading = true
        }
    }

    /**
     * 移除当前页原生广告对象
     * 当前页销毁时调用
     */
    fun removeUsedNativeAd(nativeAd: NativeAd) {
        setNativeAdListener(null)
        nativeAd.destroy()
        nativeAds.remove(nativeAd)
//        LogUtil.i("原生剩余原生广告个数：${nativeAds.size}")
//        LogUtil.i("移除当前页原生广告对象")
        if (nativeAds.isEmpty() && !loading) {
            LogUtil.i("移除对象后，预加载原生广告")
            loadNativeAds(adUnitIds)
            loading = true
        }
    }

    fun release() {
        LogUtil.i("清空原生广告 setNativeAdListener(null)")
        setNativeAdListener(null)
        releaseNativeAds()
        adUnitIds.clear()
    }

    override fun clearCache() {
        LogUtil.i("观察者模式释放 原生广告资源")
        releaseNativeAds()
        loadNativeAds(adUnitIds)
    }
}